package gate

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"

	"github.com/hwcer/cosgo"
	"github.com/hwcer/cosgo/session"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/gateway"
	"github.com/hwcer/yyds/options"
)

var securitySecretKey = map[string]string{}

func init() {
	gateway.Options.Validate = Validate
	cosgo.On(cosgo.EventTypLoaded, loadSecretFromFile)
	cosgo.On(cosgo.EventTypReload, loadSecretFromFile)
}
func Validate(p *session.Data, oath options.OAuthType, path string, query values.Metadata, body []byte) error {
	if oath == options.OAuthTypeNone || oath == options.OAuthTypeOAuth || gateway.Access.HasMaster(p) {
		return nil
	}
	k := query.GetString("k")
	if k == "" {
		return errors.Errorf(501, "args empty")
	}
	secret, ok := securitySecretKey[k]
	if !ok {
		return errors.Errorf(502, "args error")
	}
	s := query.GetString("s")
	if s == "" {
		return errors.Errorf(503, "args error")
	}

	buff := bytes.NewBuffer(body)
	buff.WriteString(secret)
	ms := MD5(buff.Bytes())
	if ms != s {
		return errors.Errorf(504, "data error")
	}
	return nil
}

func loadSecretFromFile() error {
	securitySecretKey = map[string]string{}
	// 读取文件内容
	filename := cosgo.Abs("security.json")
	data, err := os.ReadFile(filename)
	if err != nil {
		return fmt.Errorf("读取秘钥文件失败: %v", err)
	}

	// 解析 JSON
	err = json.Unmarshal(data, &securitySecretKey)
	if err != nil {
		return fmt.Errorf("解析秘钥文件失败: %v", err)
	}

	return nil
}

func MD5(data []byte) string {
	h := md5.New()
	h.Write(data)
	return hex.EncodeToString(h.Sum(nil))
}
